package com.yao.yaooj.judge;

import cn.hutool.json.JSONUtil;
import com.yao.yaooj.common.ErrorCode;
import com.yao.yaooj.exception.BusinessException;
import com.yao.yaooj.judge.codesandbox.CodeSandbox;
import com.yao.yaooj.judge.codesandbox.CodeSandboxFactory;
import com.yao.yaooj.judge.codesandbox.CodeSandboxProxy;
import com.yao.yaooj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yao.yaooj.judge.codesandbox.model.ExecuteCodeResponse;
import com.yao.yaooj.judge.strategy.*;
import com.yao.yaooj.model.dto.question.JudgeCase;
import com.yao.yaooj.judge.codesandbox.model.JudgeInfo;
import com.yao.yaooj.model.entity.Question;
import com.yao.yaooj.model.entity.QuestionSubmit;
import com.yao.yaooj.model.enums.QuestionSubmitStatusEnum;
import com.yao.yaooj.service.QuestionService;
import com.yao.yaooj.service.QuestionSubmitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionService questionService; //查询题目信息

    @Resource
    private QuestionSubmitService questionSubmitService; //查询题目提交信息

    @Value("${codesandbox.type:example}")
    private String type;

    @Resource
    private JudgeManage judgeManage;

    //1.传入题目的提交id 获取到对应的题目、提交信息（包含代码、编程语言等）
    //2.如果题目的提交状态不为等待中，就不用重复执行了
    //3.更改判题（题目提交）的状态为“判题中”，防止重复执行，也能让用户即使知道判题状态
    //4.调用沙箱，获取到执行结果
    //5.根据沙箱的执行结果，设置题目的判题列表状态和信息
    @Override
    public QuestionSubmit doJudge(Long questionSubmitId) {
        //1.根据题目提交信息，拿到题目id
        QuestionSubmit questionSubmit=questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");//提交信息不存在
        }
        //获得对应的提交信息
        Long questionId = questionSubmit.getQuestionId();
        //获得对应的题目信息
        Question question = questionService.getById(questionId);
        if(question==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交题目不存在");
        }
        //开始判题！！！
        //2.题目状态应该为等待中
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){ //如果是 == 那么判断的就是两个值的地址是否指向同一个内存
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"正在判题，请勿重复提交");
        }
        //3.即将判题，将题目状态更改为判题中
        QuestionSubmit questionSubmitUpdate=new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新失败");
        }
        //4.调用代码沙箱
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        //获取代码沙箱应该传入的参数
        String code=questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        //获取多组测试用例judgeCase！先获取每个测试用例对象列表，再获取每个测试用例的inputList列表
        List<JudgeCase> judgeCaseList= JSONUtil.toList(question.getJudgeCase(), JudgeCase.class);
        List<String> inputList=judgeCaseList.stream()
                .map(JudgeCase::getInput)
                .collect(Collectors.toList());//收集成一个列表
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .inputList(inputList)
                .language(language)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        List<String> outputList =executeCodeResponse.getOutputList();
        JudgeContext judgeContext=new JudgeContext();
        judgeContext.setOutputList(outputList);
        judgeContext.setInputList(inputList);
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);
        //5.根据沙箱的执行结果来判断题目的状态和信息
        //根据选择的语言来定义策略（不同的语言处理方式略微差别）
        JudgeInfo judgeInfo=judgeManage.doJudge(judgeContext);

        //6.修改数据库的判题结果
        questionSubmitUpdate=new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新失败");
        }
        //QuestionSubmit questionSubmitResult= questionSubmitService.getById(questionSubmitId);
        QuestionSubmit questionSubmitResult= questionSubmitService.getById(questionId);//??我觉得是上面这个呀
        return questionSubmitResult;
    }
}
